import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import '../tabs/work_tab.dart';
import '../tabs/liked_tab.dart';
import '../tabs/gallery_tab.dart';
import '../tabs/character_tab.dart';
import 'package:flutter/services.dart' show rootBundle;
import '../../tools/smscontroller.dart';
import '../../tools/loginscreen.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Sms extends StatefulWidget {
  const Sms({super.key});

  @override
  State<Sms> createState() => _SmsState();
}

class _SmsState extends State<Sms> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  bool _isButtonDisabled = true;
  bool _isCodeSent = false;
  int _countdown = 60;

  final SmsController _smsController = SmsController();
  bool _isBlurActive = false;
  bool _isInviteCodeBoxVisible = false;

  void _updateState() {
    setState(() {
      _isCodeSent = true;
      _startCountdown();
    });
  }

  void _startCountdown() {
    Future.delayed(Duration(seconds: 1), () {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
        _startCountdown();
      } else {
        setState(() {
          _isCodeSent = false;
          _countdown = 60;
        });
      }
    });
  }

  void _verifyCodeAndLogin(String phoneNumber, String code) async {
    final response = await http.post(
      Uri.parse('http://43.134.218.65:5004/verify_code'),
      headers: <String, String>{
        'Content-Type': 'application/json',
      },
      body: jsonEncode(<String, String>{
        'phone_number': phoneNumber,
        'code': code,
      }),
    );

    if (response.statusCode == 200) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录成功')),
      );
      setState(() {
        GlobalState.isLoggedIn.value = true; // 确保登录状态更新
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('手机号或验证码错误')),
      );
    }
  }

  void _showLogoutDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认退出'),
          content: Text('你确定要退出登录吗？'),
          actions: [
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('确定'),
              onPressed: () {
                setState(() {
                  GlobalState.reset();
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _showInviteCodeBox() {
    setState(() {
      _isBlurActive = true;
      _isInviteCodeBoxVisible = true;
    });
  }

  void _closeInviteCodeBox() {
    setState(() {
      _isBlurActive = false;
      _isInviteCodeBoxVisible = false;
    });
  }

  Future<void> _saveImage() async {
    print('保存图片88888');
    print("_onImageSaveButtonPressed");

    ByteData bytes = await rootBundle.load('lib/assets/初稿.png');
    final result = await ImageGallerySaver.saveImage(bytes.buffer.asUint8List()); //这个是核心的保存图片的插件
    print(result);   //这个返回值 在保存成功后会返回true

    if (result != null && result["isSuccess"]) {
      _showOverlay(context, '保存图片成功');
    } else {
      Fluttertoast.showToast(
        msg: '保存失败',
        fontSize: 14,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        textColor: Colors.white,
      );
    }
  }

  void _showOverlay(BuildContext context, String message) {
    OverlayEntry overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        top: MediaQuery.of(context).size.height * 0.4,
        left: MediaQuery.of(context).size.width * 0.1,
        right: MediaQuery.of(context).size.width * 0.1,
        child: Material(
          color: Colors.transparent,
          child: Container(
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.7),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Center(
              child: Text(
                message,
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            ),
          ),
        ),
      ),
    );

    Overlay.of(context)?.insert(overlayEntry);

    Future.delayed(Duration(seconds: 2), () {
      overlayEntry.remove();
    });
  }

  void _showLoginSheet() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return AddTaskScreen(); // 登录的上拉框
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      valueListenable: GlobalState.isLoggedIn,
      builder: (context, isLoggedIn, child) {
        return DefaultTabController(
          length: 4,
          child: Scaffold(
            drawer: Drawer(
              child: ListView(
                padding: EdgeInsets.zero,
                children: <Widget>[
                  DrawerHeader(
                    child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              CircleAvatar(
                                radius: 40,
                                backgroundColor: Colors.grey,
                                backgroundImage: AssetImage(GlobalState.avatarPath),
                              ),
                              SizedBox(height: 8),
                              Text(GlobalState.username, style: TextStyle(color: Colors.white)),
                            ]
                    ),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                    ),
                  ),
                  if (isLoggedIn)
                    ListTile(
                      leading: Icon(Icons.edit),
                      title: Text('编辑资料'),
                      trailing: Icon(Icons.keyboard_arrow_right),
                      onTap: () {
                        // 添加相应的点击事件
                      },
                    ),
                  ListTile(
                    leading: Icon(Icons.card_giftcard),
                    title: Text('邀请码 / 兑换电量'),
                    trailing: Icon(Icons.keyboard_arrow_right),
                    onTap: () {
                      Navigator.of(context).pop(); // 关闭侧边栏
                      _showInviteCodeBox(); // 显示邀请码盒子
                    }, // 添加相应的点击事件
                  ),
                  ListTile(
                    leading: Icon(Icons.lock),
                    title: Text('隐私设置'),
                    trailing: Icon(Icons.keyboard_arrow_right),
                    onTap: () {
                      Navigator.pushNamed(context, '/settings');
                    }, // 添加相应的点击事件
                  ),
                  ListTile(
                    leading: Icon(Icons.feedback),
                    title: Text('意见反馈'),
                    trailing: Icon(Icons.keyboard_arrow_right),
                    onTap: () {
                      Navigator.pushNamed(context, '/feedback');
                    }, // 添加相应的点击事件
                  ),
                  ListTile(
                    leading: Icon(Icons.report),
                    title: Text('举报'),
                    trailing: Icon(Icons.keyboard_arrow_right),
                    onTap: () {
                      Navigator.pushNamed(context, '/alarm');
                    }, // 添加相应的点击事件
                  ),
                  ListTile(
                    leading: Icon(Icons.info),
                    title: Text('关于识海'),
                    trailing: Icon(Icons.keyboard_arrow_right),
                    onTap: () {
                      Navigator.pushNamed(context, '/guanyu');
                    }, // 添加相应的点击事件
                  ),
                  if (isLoggedIn)
                    ListTile(
                      leading: Icon(Icons.logout),
                      title: Text('退出登录'),
                      trailing: Icon(Icons.keyboard_arrow_right),
                      onTap: _showLogoutDialog,
                    ),
                ],
              ),
            ),
            body: Stack(
              children: [
                Column(
                  children: [
                    Stack(
                      children: [
                        Container(
                          height: 310,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage("lib/assets/background.png"),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        Positioned(
                          top: 30,
                          left: 16,
                          right: 16,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Builder(
                                builder: (context) => IconButton(
                                  icon: Icon(Icons.menu, color: Colors.white),
                                  onPressed: () => Scaffold.of(context).openDrawer(),
                                ),
                              ),
                              Icon(Icons.notifications, color: Colors.white),
                            ],
                          ),
                        ),
                        Positioned(
                          top: 50,
                          left: 0,
                          right: 0,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              CircleAvatar(
                                radius: 40,
                                backgroundColor: Colors.grey,
                                backgroundImage: AssetImage(GlobalState.avatarPath),
                              ),
                              SizedBox(height: 8),
                              Text(GlobalState.username, style: TextStyle(color: Colors.white)),
                              SizedBox(height: 4),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      if (isLoggedIn) {
                                        Navigator.pushNamed(context, '/guanzhu');
                                      } else {
                                        _showLoginSheet();
                                      }
                                    },
                                    child: Text('关注 ${GlobalState.followers}', style: TextStyle(color: Colors.white)),
                                  ),
                                  SizedBox(width: 8),
                                  GestureDetector(
                                    onTap: () {
                                      if (isLoggedIn) {
                                        Navigator.pushNamed(context, '/fensi');
                                      } else {
                                        _showLoginSheet();
                                      }
                                    },
                                    child: Text('粉丝 ${GlobalState.fans}', style: TextStyle(color: Colors.white)),
                                  ),
                                  SizedBox(width: 8),
                                  GestureDetector(
                                    onTap: () {
                                      if (isLoggedIn) {
                                        Navigator.pushNamed(context, '/huozan');
                                      } else {
                                        _showLoginSheet();
                                      }
                                    },
                                    child: Text('获赞 ${GlobalState.likes}', style: TextStyle(color: Colors.white)),
                                  ),
                                  SizedBox(width: 8),
                                  GestureDetector(
                                    onTap: () {
                                      if (isLoggedIn) {
                                        Navigator.pushNamed(context, '/tong');
                                      } else {
                                        _showLoginSheet();
                                      }
                                    },
                                    child: Text('被拍同款 ${GlobalState.sameShot}', style: TextStyle(color: Colors.white)),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Positioned(
                          top: 180,
                          left: 0,
                          right: 0,
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  height: MediaQuery.of(context).size.height * 0.05,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(20.0),
                                    gradient: LinearGradient(
                                      colors: [Colors.purple, Colors.blue],
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                    ),
                                  ),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          SizedBox(width: 8),
                                          Icon(Icons.flash_on, color: Colors.white),
                                          SizedBox(width: 4),
                                          Text('电量获取进度：0/0', style: TextStyle(color: Colors.white)),
                                        ],
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(right: 10),
                                        child: SizedBox(
                                          width: 80,
                                          height: 30,
                                          child: ElevatedButton(
                                            style: ButtonStyle(
                                              minimumSize: MaterialStateProperty.all(Size.zero),
                                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                              padding: MaterialStateProperty.all(const EdgeInsets.only(left: 15, right: 15, top: 4, bottom: 4)),
                                              backgroundColor: MaterialStateProperty.all(Color.fromARGB(255, 154, 53, 255)),
                                            ),
                                            onPressed: () {},
                                            child: Text('领取电量', style: TextStyle(color: Colors.white, fontSize: 12.0)),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(height: 8),
                                LinearProgressIndicator(
                                  value: 0.0,
                                  backgroundColor: Colors.grey,
                                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                ),
                                SizedBox(height: 8),
                                Container(
                                  height: MediaQuery.of(context).size.height * 0.05,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(20.0),
                                    gradient: LinearGradient(
                                      colors: [Colors.blue, Colors.purple],
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                    ),
                                  ),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          SizedBox(width: 8),
                                          Icon(Icons.local_offer, color: Colors.white),
                                          SizedBox(width: 4),
                                          Text('识海充电站-限时特惠', style: TextStyle(color: Colors.white)),
                                        ],
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(right: 10),
                                        child: SizedBox(
                                          width: 50,
                                          height: 30,
                                          child: ElevatedButton(
                                            style: ButtonStyle(
                                              minimumSize: MaterialStateProperty.all(Size.zero),
                                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                              padding: MaterialStateProperty.all(const EdgeInsets.only(left: 10, right: 10, top: 4, bottom: 4)),
                                              backgroundColor: MaterialStateProperty.all(Color.fromARGB(255, 53, 97, 255)),
                                            ),
                                            onPressed: () {},
                                            child: Text('Go!', style: TextStyle(color: Colors.white, fontSize: 12.0)),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      color: Colors.white,
                      child: TabBar(
                        labelColor: Colors.black,
                        unselectedLabelColor: Colors.grey,
                        tabs: [
                          Tab(text: '作品'),
                          Tab(text: '赞过'),
                          Tab(text: '图库'),
                          Tab(text: '角色'),
                        ],
                      ),
                    ),
                    Expanded(
                      child: TabBarView(
                        children: [
                          WorkTab(),
                          LikedTab(),
                          GalleryTab(),
                          CharacterTab(),
                        ],
                      ),
                    ),
                  ],
                ),
                if (_isBlurActive)
                  GestureDetector(
                    onTap: _closeInviteCodeBox,
                    child: BackdropFilter(
                      filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
                      child: Container(
                        color: Colors.black.withOpacity(0.5),
                        alignment: Alignment.center,
                        child: _isInviteCodeBoxVisible
                            ? Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  SizedBox(height: 40),
                                  Image.asset(
                                    'lib/assets/初稿.png',
                                    width: MediaQuery.of(context).size.width * 0.85,
                                  ),
                                  SizedBox(height: 40),
                                  ElevatedButton(
                                    onPressed: _saveImage,
                                    child: Text('保存图片'),
                                  ),
                                  SizedBox(height: 80),
                                  ElevatedButton(
                                    style: ButtonStyle(
                                      side: MaterialStateProperty.all(BorderSide(width: 1, color: Color(0xffCAD0DB))),
                                      shape: MaterialStateProperty.all(BeveledRectangleBorder(borderRadius: BorderRadius.circular(32))),
                                    ),
                                    onPressed: _closeInviteCodeBox,
                                    child: Text('×'),
                                  ),
                                ],
                              )
                            : null,
                      ),
                    ),
                  ),
              ],
            ),
            floatingActionButton: _isBlurActive
                ? null
                : Stack(
                    children: [
                      Positioned(
                        width: 40,
                        height: 80,
                        bottom: 80.0,
                        right: -10.0,
                        child: FloatingActionButton(
                          heroTag: 'feedbackButton',
                          onPressed: () {
                            Navigator.pushNamed(context, '/feedback');
                          },
                          backgroundColor: Color.fromARGB(255, 102, 86, 210),
                          child: RotatedBox(
                            quarterTurns: 3,
                            child: Text('点我反馈', style: TextStyle(color: Colors.white, fontSize: 12.0)),
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.bottomRight,
                        child: FloatingActionButton(
                          onPressed: () {},
                          child: Container(
                            width: 60,
                            height: 60,
                            child: Icon(
                              Icons.add,
                              color: Colors.white,
                            ),
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: ExactAssetImage('lib/assets/ali.png'),
                                fit: BoxFit.cover,
                              ),
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
            floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
          ),
        );
      },
    );
  }
}

class TabItem extends StatelessWidget {
  final String text;

  const TabItem(this.text, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20.0),
      child: Text(text, style: TextStyle(color: Colors.black)),
    );
  }
}

class BottomNavItem extends StatelessWidget {
  final IconData icon;
  final String label;

  const BottomNavItem(this.icon, this.label, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: Colors.grey),
          Text(label, style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }
}
